var util = require('../../../utils/util.js');
var app = getApp();
var plugin = requirePlugin("myPlugin");
var dingdanPage;  //存放上一个页面的信息
var complete_ck;  //是否点击了删除或恢复订单返回
var OrderList; //存放上一个页面的列表
Page({
  /**
   * 页面的初始数据
   */
  data: {
    reason:'', //退回原因
    quxiaodingdan:'',  //取消原因
    tszhinput:'', //商品备注
    order_remark:'', //订单备注
    content:'', //键盘初始空字符串
    inputNum: "",    //添加商品弹窗的输入框中数量
    isInput:false,  //带键盘弹窗
    isOrderremark:false,  //订单备注
    isShopremark:false,  //商品备注
    ischeck_pass:false, //审核通过
    isBackUpdate: false,  //退回修改弹窗
    is_setdel:false, //是否删除订单
    KeyboardKeys: [1, 2, 3, 4, 5, 6, 7, 8, 9, '·', 0], //键盘
    is_checked:{},  //单选
    is_checkall: false,
    count:0,  //选中数量
    isChooseAll: false,    //全选
    isreturn:false,   //是否退货
    isreturn_sub:false, //退单弹窗
    shou_num_arr:[],  //实际收货数量数组
    isshou_show:false, //收货合计栏显示
    all_shou:0,  //收货总合计
    weightstatus: false, //是否启用蓝牙秤
    connectionstate: "未连接", //打印机连接情况
    cont: "未连接", //电子秤连接情况
    return_len:0,   //剔除不可退的商品数
    isreject:false,  //审核驳回弹窗
    isme_fill:false, //是否自填报价
    is_offchange:false,   //填写报价弹窗
    showfocus:false,
    is_change:1, //1代表可以修改，2代表锁定
    ishint_ping:false,   //
    specsunit:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    complete_ck=false;
    const pages = getCurrentPages();    //获取当前页面信息栈
    dingdanPage = pages[pages.length - 2]; //获取上一个页面信息 
    console.log(dingdanPage.data.status);
    if(dingdanPage.data.status==0){  //新需求单
      OrderList = dingdanPage.data.helist;   
    }else if(dingdanPage.data.status==10){  //历史记录
      OrderList = dingdanPage.data.datas;  
    };
    this.setData({
      unit_height:0.64* wx.getSystemInfoSync().windowHeight,
      entPage:options.entPage,
      d_index:options.d_index,  //列表的索引
      is_created:options.is_created,   //是否询价转过正式单
      is_enquiry:options.is_enquiry,   //是否为询价单
      use_person_id:app.globalData.person_id, //当前用户的个人id
      group_id:app.globalData.group_id,  //是否为集团版
      id: options.id,
      good_dir_set:app.globalData.loginInfo.good_dir_set,
      order_status:options.order_status,
      check_type:options.check_type,
      title_index:options.title_index  //1订单详情或需求单;2采购单详情;
    });
    var that = this;
    wx.setNavigationBarTitle({
      title: options.settitle+"详情"
    });
    app.AppHttp('api/Client/KitchenManage', {  //判断审核权限开关
      id: app.globalData.loginInfo.id
    }, function (res) {
      console.log(JSON.stringify(res.data));
      that.setData({
        check_open_close: res.data.ClientFind.check_open_close
      });
    });      
  },
  noneEnoughPeople:function(){
    return;
  },
  onloadDetail: function (){
    var that = this;
    wx.showLoading({
      title: '加载中...',
    });
    app.AppHttp('api/Order/SmallOrderDetail', {
      id: that.data.id,
      openid: app.globalData.openid,
      check_type:that.data.check_type
    }, function (res) {
      console.log(JSON.stringify(res.data));       
      var goodList=res.data.orderDetail.goodList; 
      var valid;
      if (res.data.orderDetail.level == 1) {  //向供应商端下单
        valid = 'valid';
      } else if (res.data.orderDetail.level == 4) { //向批发端下单
        valid = 'pf_supplier';
      }else{
        valid='';
      };
      var info=res.data.orderDetail;  
      that.check_list(info.order_status);
      that.setData({
        offer_price_list:Array(goodList.length).fill(''),  //初始(每一项为'')报价数组
        shou_num_arr:[],  //实际收货数量数组
        is_enquiry:res.data.orderDetail.is_enquiry,
        isreturn:false,
        return_len:0,
        isshou_show:false,
        all_shou:0,
        goodList: goodList,
        info: res.data.orderDetail,
        rev_order_log:res.data.orderDetail.order_log.reverse(),
        level: res.data.orderDetail.level,
        valid:valid,
        auth_type: res.data.auth_type,
        order_status: res.data.orderDetail.order_status,
        delivery_date_name: res.data.orderDetail.delivery_date_name,
        create_timeS:util.formatTime(new Date(res.data.orderDetail.create_timeS*1000)).substring(0,10),
        song_time:res.data.orderDetail.set_songhuo_time>0?util.formatTime(new Date(res.data.orderDetail.set_songhuo_time*1000)).substring(0,10):0
      });
      if(res.data.orderDetail.order_status==7){  //状态7时,调用评价
        that.comment_list();
      }
      if(goodList.length>0){
        that.child = that.selectComponent('.plug-data');    
        if(info.return_type==1 && that.data.use_person_id==info.person_id
          && (info.order_status == -1 || info.order_status == -2)
        ){ //恢复左滑
          that.child.change_move(false);
          console.log('恢复');
          console.log(that.child);
        }else{//禁止左滑
          console.log('禁止');
          for(var i=0;i<goodList.length;i++){
            that.manychild = that.selectComponent('#plug-data'+[i]);
            that.manychild.closeButtonGroup();
          }
          that.child.change_move(true);       
        };
      }
      wx.hideLoading(); 
    })   
  },
  /**
   * 选择时间
   */
  bindDateChange(e){
    let that = this;
    app.AppHttp('api/Orders/setOrderSetSongHuoTime', {  
      order_id:that.data.id,
      set_songhuo_time:e.detail.value
    }, function (res) {
      if(res.data.status==1){
        wx.showToast({
          title:'设置成功',
        });
        that.setData({
          song_time:e.detail.value
        });
      }else{
        wx.showToast({
          title:'设置失败',
        });
      };
    });
  },
  /**
 * 点击电话图标给客户打电话
 */
telphone(){
  if(app.globalData.test==1){
    wx.showLoading({
      title: '暂无权限',
      duration: 500
    });
    return;
  };
  let phoneNumber;
  if(this.data.info.docking_id>0 && this.data.info.docking_phone){
    phoneNumber=this.data.info.docking_phone;
  }else if(this.data.info.alias_id_default>0 && this.data.info.alias_phone){
    phoneNumber=this.data.info.alias_phone;
  }else{
    phoneNumber=this.data.info.supplier_phone;
  };
  wx.makePhoneCall({
    phoneNumber: phoneNumber
  });
},
  // 评价详情
  comment_list(){
    var that = this;
    wx.request({  
      url: app.globalData.url + 'get_order_comment/'+that.data.id,
      method: "GET",
      success: function(res) {
        console.log(JSON.stringify(res.data));  
        that.setData({
          comm_list:res.data
        });
      }
    });  
  },
  // 审核流程数据
  check_list(order_status){
    let that = this;
    app.AppHttp('api/Order/getOrderCheck', {
      order_id:that.data.id,
      check_type:order_status<4?"purchase_order":"receipt_order"
    }, function (res) {
      console.log(JSON.stringify(res.data));
      var check_step=-1;
      // var is_incheck=-1;
      let isme_back=-1; 
      if(res.data.check_order_list.length>0){  
        check_step=0;
        // is_incheck = res.data.check_order_list.findIndex(function(item) {
        //   return item.id == app.globalData.person_id;
        // });
        if(order_status==-1){
          isme_back = res.data.check_order_list.findIndex(function(item) {
            return item.is_checked == -1;
          });
        };
      };  
      console.log(check_step);
      that.setData({
        check_type:order_status<4?"purchase_order":"receipt_order",
        check_list:res.data,
        check_step:check_step, //-1表示无审核人  0表示有审核人
        isme_back:isme_back   //是否发起人自己撤回==-1  自己撤回；>-1其他人撤回
        // // is_incheck:is_incheck,  //当前用户是否是审核人，>-1是，值代表他是第几个审核人；==-1，不是审核人
      });  
    }); 
  },
  // 去评价
  to_eval(){
    this.cancel_hint_ping();
    wx.navigateTo({
      url:'/pages/dingdan/order_detail/evaluation/evaluation?id='+this.data.id
    });
    // wx.navigateTo({
    //   url:'/eval_space/pages/evaluation/evaluation?id='+this.data.id
    // });
  },
  new_to_eval(){
     wx.navigateTo({
      url:'/eval_space/pages/evaluation/evaluation?id='+this.data.id
    });
  },
  // 前往对账
  toduizhang:function(){
    var info=this.data.info;
    var val={};
    var is_zi_cai=0;
    if(info.zicai_id>0){  //自采
      val= {'logo':info.client_logo,'company_name':info.customer_name,'real_name':info.real_name,'status':info.coop_status,'phone':info.phone};
      is_zi_cai=1;
    }else{
      val= {'logo':info.supplier_logo,'company_name':info.company_name,'real_name':info.supplier_real_name,'status':info.coop_status,'phone':info.supplier_phone};
    }
    wx.navigateTo({
      url: '/super_space/pages/supper/supperguanli/supperguanli?id='+ info.supplier_id+"&val="+JSON.stringify(val)+'&is_zi_cai='+is_zi_cai
    });  
  },
  // 申请退单
  apply_return:function(){
    var return_len=0;
    var goodList = this.data.goodList.map(function(item) {
      item.return_num=Math.abs(item.return_num*1);
      if(item.return_num*1-item.refer_num*1-item.loss_num*1==0){
        return_len++;
      };
      return (item);
    });
    this.setData({
      goodList:goodList,
      return_len:return_len,
      isreturn:true 
    });
  },
  // 取消退单申请
  apply_rn_cancel:function(){
    this.setData({
      isreturn:false
    })
  },
  // 联系供应商
  contact_super:function(){
    if(app.globalData.test==1){
      wx.showLoading({
        title: '暂无权限',
        duration: 500
      });
      return;
    };
    wx.makePhoneCall({
      phoneNumber: this.data.info.supplier_phone
    });
  },
  // 再来一单
  again_butck:function(){
    var that = this;
    util.buttonClicked(this);  //防止重复点击
    app.AppHttp('api/Order/AgainOrder', {
      openid: app.globalData.openid,
      id: that.data.id
    }, function (res) {
      app.globalData.dingdan_show = 1;  //返回订单页面是否刷新
      app.globalData.toneed_order=1; //返回新订单
      wx.showToast({
        title: res.data.msg
      })
      wx.navigateBack({
        delta: 1
      })
    });     
  },
  // 增加商品
  addshangpin:function(){
    var order_status = this.data.order_status;
    var supplier_name=this.data.info.company_name?this.data.info.company_name:''
    var is_zi_cai=this.data.info.zicai_id>0?1:0
    wx.navigateTo({
      url: '../../shangpin/shangpindetail/addsearch/addsearch?order_id=' + this.data.id + '&supplier_id=' + this.data.info.supplier_id +'&order_status=' + order_status+'&supplier_name='+supplier_name+'&is_zi_cai='+is_zi_cai+'&is_open_standard='+this.data.info.is_open_standard
    })
  },
  // 滑动删除该商品
  deleteOutOrder: function (event){
    var that = this;
    var shopid = event.currentTarget.dataset.id;
    if(that.data.goodList.length==1){
      wx.showModal({
        title: '提示',
        content: "只有一个商品了,不能清空此单",
        showCancel: false,
        confirmText:"我知道了",
        success: function (res) {}
      });
    }else{
      wx.showModal({
        title: '提示',
        content: '请确认删除',
        success: function (res) {
          if (res.confirm) {
            app.UpAsso('java_order/update_order_allow_batch/'+this.data.id, //订单关联
              function (ress) {
            });
            app.globalData.dingdan_show = 1;  //返回订单页面是否刷新
            app.myMethod.updataDingdanGood(shopid, that.data.id,0, that.data.tszhcontent);
            that.onloadDetail(); 
          }
        }
      });
    };       
  },
  //打开退回修改弹窗
  open_backupdate: function () {
    this.setData({
      isBackUpdate: true
    });
  },
  // 关闭退回修改弹窗
  backupdatecancel:function(){
    this.setData({
      isBackUpdate: false
    });
  },
  //填写退回原因
  setMsg: function (e) {
    this.setData({
      reason:e.detail.value
    })
  },
  //确定退回修改
  backupdateconfirm: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.request({
      url: app.globalData.url + 'api/Order/returnUpdate',
      method: "POST",
      data: {
        openid: app.globalData.openid,
        id: id,
        reasons_returning: that.data.reason
      },
      success: function (res) {
        if (res.data.status == 1) {
          that.setData({
            order_status:-1,
            isBackUpdate: false
          });  
          that.onloadDetail(); 
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'loading',
            duration: 500,
          })
        }
      }
    })
  },
  // 打开审核通过
  open_pass:function(){
    this.setData({
      ischeck_pass:true
    });
  },
  // 关闭审核通过
  pass_cancel:function(){
    this.setData({
      ischeck_pass:false
    });
  },
  // 审核同意
  tongyi_but:function(){
    var that=this;
    app.AppHttp('api/Order/normalOrderCheck', {
      openid: app.globalData.openid,
      order_id: that.data.id,
      check_type:'resolve',   //正常审核
      check_field:that.data.check_type
    }, function (res) {
      console.log(JSON.stringify(res.data));
      app.globalData.dingdan_show = 1;
      app.globalData.caigou_shua=1;
      if(res.data.data.finish == 1){
        if(that.data.check_type=="purchase_order"){
          that.okClick();
        };   
      }else{
        wx.navigateBack({
          delta:1
        });
        that.valid_news(that.data.id,'client_order_check');
        that.onloadDetail();
      };
    })
  },
  // 审核驳回
  reject_but:function(){
    this.setData({
      isreject:true,
      reject_reason:''
    });
  },
  // 关闭驳回
  cancel_reject:function(){
    this.setData({
      isreject:false
    });
  },
  // 输入驳回原因
  inputreject:function(e){
    this.setData({
      reject_reason:e.detail.value
    });
  },
  // 确定驳回
  conf_reject:function(){
    var that=this;
    console.log(that.data.reject_reason);
    app.AppHttp('api/Order/normalOrderCheck', {
      openid: app.globalData.openid,
      order_id: that.data.id,
      check_type:'reject',  //驳回
      reject_reason:that.data.reject_reason,
      check_field:that.data.check_type
    }, function (res) {
      console.log(JSON.stringify(res.data));
      if(that.data.entPage==1){
        app.globalData.dingdan_show = 1;
        app.globalData.caigou_shua=1;
      }; 
      that.setData({
        order_status:-1,
        isreject:false
      });
      wx.navigateBack({
        delta:1
      });
    });
  },
  //审核通过
  okClick: function () {
    var that = this;
    app.AppHttp('api/Order/changeOrderStatus', {  
      openid:app.globalData.openid,
      id: that.data.id,
      status:1
    }, function (res) {
      console.log(JSON.stringify(res.data));
      if (res.data.status == 1) {
        app.globalData.dingdan_show = 1;  //返回订单页面是否刷新  
        app.globalData.caigou_shua=1;  //返回订单页面是否刷新        
        that.valid_news();          
        wx.navigateBack({
          delta:1
        });           
      } else {
        wx.showToast({
          title: '提交失败',
          icon: 'loading',
          duration: 500,
        })
      }    
    });
  },
  // 库管接单
  keeper_order:function(){
    var that = this;
    app.AppHttp('api/Order/changeOrderStatus', {  
      openid:app.globalData.openid,
      id: that.data.id,
      status:2
    }, function (res) {
      console.log(JSON.stringify(res.data));
      if (res.data.status == 1) {
        app.globalData.dingdan_show = 1;  //返回订单页面是否刷新  
        app.globalData.caigou_shua=1;  //返回订单页面是否刷新  
        wx.navigateBack({
          delta:1
        });           
      } else {
        wx.showToast({
          title: '接单失败',
          icon: 'loading',
          duration: 500,
        })
      }    
    });
  },
  // 查看日志
  see_log:function(){
    util.showBuyModal(this);
    this.setData({
      is_many_allow:true
    });
  },
  // 关闭日志
  close_log:function(){
    util.hideBuyModal(this,'is_many_allow');
  },
  // 打开删除订单弹窗
  set_del: function () {
    this.setData({
      is_setdel:true
    });
  },
  // 关闭删除订单弹窗
  set_delcancel: function () {
    this.setData({
      is_setdel: false
    })
  },
  // 确定删除订单
  set_delconfirm:function(){
    var that = this;
    app.AppHttp('api/Order/delete_order', {
      openid: app.globalData.openid,
      id: that.data.id
    }, function (res) {
      console.log(JSON.stringify(res.data))
      if (res.data.status == 1) {
        wx.showToast({
          title: '删除成功',
          icon: 'loading',
          duration: 500,
        });
        app.globalData.dingdan_show = 1;  //返回订单页面是否刷新
        app.globalData.caigou_shua=1;  //返回订单页面是否刷新  
        wx.navigateBack({
          delta:1
        });
      } else {
        wx.showToast({
          title: '删除失败',
          icon: 'loading',
          duration: 500,
        })
      }
    })
  },
  // 待编辑状态提交
  set_edit:function(){
    var that = this;
    app.AppHttp('api/Order/updateFinishOrder', {
      openid: app.globalData.openid,
      id: that.data.id,
      order_type:'z'
    }, function (res) {
      if (res.data.status == 1) {
        if(that.data.check_open_close==0){  //审核关闭时发模板消息
          that.valid_news();
        }; 
        if(that.data.title_index==1){
          app.globalData.dingdan_show = 1;  //返回订单页面是否刷新
          wx.navigateBack({
            delta:1
          });
        }else if(that.data.title_index==2){
          app.globalData.caigou_shua=1;  //返回订单页面是否刷新
          wx.navigateBack({
            delta:1
          });
        }
      } else {
        wx.showToast({
          title: '提交失败',
          icon: 'loading',
          duration: 500,
        })
      }
    })
  },
  // 模板消息
  valid_news:function(id,check){
    var that = this;
    console.log('valid_news');
    wx.request({
      url: app.globalData.url + 'api/Message1/valid',
      method: 'GET',
      data: {
        id: id?id:that.data.id,
        message_type:check?check:that.data.valid
      },
      success: function (res) {
        console.log(JSON.stringify(res.data));
      }
    });
  },
  // 重新提交订单
  resetOrder: function (e) {
    var id = e.currentTarget.dataset.id;
    var that = this;
    var status=0;
    if(that.data.check_open_close==0){  //审核关闭
      status=1;
    };
    if(that.data.info.zicai_id>0){   //自采
      status=3;
    }
    wx.request({
      url: app.globalData.url + 'api/Order/changeOrderStatus',
      method: "POST",
      data: {
        openid:app.globalData.openid,
        id: id,
        status:status,
        field:that.data.check_type,
        reset:1
      },
      success: function (res) {
        console.log(res.data);
        console.log(that.data.check_type)
        if (res.data.status == 1) {
          if(status==1){  //审核关闭
            // that.valid_news();
            that.setData({
              order_status:1
            });
            dingdanPage.setData({
              ["helist[" + that.data.d_index + "].order_status_name"]:'待接单'
            });
          }else if(status==0){ //审核开放
            that.valid_news(that.data.id,'client_order_check');
            that.setData({
              order_status:0
            });
            if(that.data.check_list.check_order_list.length>0){
              dingdanPage.setData({
                ["helist[" + that.data.d_index + "].current_head_portrait"]:that.data.check_list.check_order_list[0].head_portrait,
                ["helist[" + that.data.d_index + "].current_id"]:that.data.check_list.check_order_list[0].id
              }); 
              that.setData({
                order_status:0,          
                ["check_list.current_personal"]:that.data.check_list.check_order_list[0].id
              });
            }else{
              dingdanPage.setData({
                ["helist[" + that.data.d_index + "].current_id"]:null
              });
            };    
          }else if(status==3){  //自采
            that.setData({
              order_status:3
            });
            dingdanPage.setData({
              ["helist[" + that.data.d_index + "].order_status_name"]:'备货'
            });
          };
          wx.navigateBack({
            delta:1
          }); 
        } else {
          wx.showToast({
            title: '提交失败',
            icon: 'loading',
            duration: 500,
          })
        }
      }
    })
  },
  // 恢复订单
  renew_but:function(){
    var that = this;
    wx.showModal({
      title: '提示',
      content: '请确认恢复此单',
      success: function (res) {
        if (res.confirm) {
          app.AppHttp('api/Order/changeOrderStatus', {  
            openid:app.globalData.openid,
            id: that.data.id,
            status:-2
          }, function (res) {
            console.log(JSON.stringify(res.data));
            if(that.data.title_index==1){
              app.globalData.dingdan_show = 1;  //返回订单页面是否刷新     
            }else if(that.data.title_index==2){
              app.globalData.caigou_shua=1;  //返回订单页面是否刷新      
            };
            wx.navigateBack({
              delta:1
            });     
          });
        }
      }
    });
  },
  /**
   * 取消审核通过的订单
   */
  cancelOrder:function(e){
    var that = this;
    var id = e.currentTarget.dataset.id;
    that.setData({
      isCancel:true,
      id:id
    }) 
  },
  quxiaoreason:function(e){
    this.setData({
      quxiaodingdan: e.detail.value
    })
  },
  // 关闭取消订单的弹窗
  cancel: function () {
    this.setData({
      isCancel:false
    });
  },
  /**
   * 确认取消订单
   */
  confirm1:function(){
    var that = this;
    var id = that.data.id;
    wx.request({
      url: app.globalData.url + 'api/Order/ApplyCancelOrder',
      method: "POST",
      data: {
        openid:app.globalData.openid,
        id: id,
        reasons_returning: that.data.quxiaodingdan
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.status == 1) {
          that.setData({
            isCancel: false
          });
          if(that.data.title_index==2){
            app.globalData.caigou_shua = 1;  //返回采购页面是否刷新
          }else if(that.data.title_index==1){
            app.globalData.dingdan_show = 1;  //返回订单页面是否刷新
          };
          wx.navigateBack({
            delta:1
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'loading',
            duration: 1000
          })
        }
      }
    })
  },
  // 编辑商品(下单量或采购)
  add_shop_but:function(e){
    util.showBuyModal(this);     
    var index = e.currentTarget.dataset.index;
    var info = this.data.info.goodList[index];
    var tannum=info.pr_num;  
    var tan_return_num;
    if(this.data.isreturn==true){        
      tannum=info.refer_num;        
      tan_return_num=tannum*1-Math.abs(info.return_num*1)-info.loss_num*1;
      tannum=tan_return_num;
      if(info.myreturn_num){
        tannum=info.myreturn_num;
      };    
    };
    this.setData({
      content:'',
      inputNum:'',
      isInput: true,
      inputIndex: index,
      tanimg: info.pr_cover,
      tanname: info.pr_name,
      tanalias: info.pr_alias,
      tanspecs:info.specs,
      tanunit:info.true_unit_name!='无'?info.true_unit_name:info.unit_name,
      tan_prnum:info.pr_num,
      tannum: tannum,
      tan_return_num:tan_return_num,    //可退值
      tszhcontent: info.detail_remark?info.detail_remark:''
    }); 
  },
  // 收货入库数量编辑
  add_shou_but:function(e){
    util.showBuyModal(this);
    var index = e.currentTarget.dataset.index;
    var info = this.data.info.goodList[index];
    var tannum;
    if(info.shou_num){
      tannum=info.shou_num;
    }else{
      tannum=this.data.info.is_single==1 && this.data.info.is_nuified_num==1?info.single_num:info.need_num;
    };
    this.setData({
      content:'',
      inputNum:'',
      isInput: true,
      inputIndex: index,
      tanimg:info.pr_cover,
      tanname: info.pr_name,
      tanalias: info.pr_alias,
      tanspecs:info.specs,
      tanunit:info.true_unit_name!='无'?info.true_unit_name:info.unit_name,
      tan_prnum:info.pr_num,
      tannum: tannum,
      tszhcontent: info.detail_remark?info.detail_remark:''
    });
  },
  // 关闭底部商品弹窗
  add_shop_cancel:function(){
    util.hideBuyModal(this,"isInput");
  },
  // 键盘按键
  keyTap(e) {
    util.keyfunction(e,this,3);
    this.setValue();
  },
  setValue: function () {
    this.setData({
      inputNum: this.data.content
    });
  },
  // 打开商品备注
  open_remark_sh:function(){
    this.setData({
      isShopremark:true,
      tszhinput:this.data.tszhcontent
    });
  },
  // 关闭商品备注
  tszhcancel: function () {
    this.setData({
      isShopremark: false
    });
  },
  // 输入商品备注
  tszhinput: function (e) {
    this.setData({
      tszhinput: e.detail.value
    })
  },
  // 确定并关闭商品备注
  tszhconfirm: function () {
    this.setData({
      isShopremark: false,
      tszhcontent: this.data.tszhinput
    })
  },
  // 确定商品
  shop_confirm: function () {
    if (this.data.inputNum == '') {
      this.setData({
        inputNum:this.data.tannum
      });
    }
    var info = this.data.info.goodList[this.data.inputIndex];
    if (this.data.inputNum>9999.99){
      wx.showToast({
        title: '数量过大',
      })
      return;
    }
    info.pr_num = this.data.inputNum == '' ? 0:parseFloat((this.data.inputNum*1).toFixed(2));
    if(this.data.goodList.length==1 && info.pr_num==0){
      wx.showModal({
        title: '提示',
        content: "只有一个商品了,不能清空此单",
        showCancel: false,
        confirmText:"我知道了",
        success: function (res) {}
      });
      return;
    }; 
    info.subtotal = (info.pr_num*info.unit_price*1).toFixed(2);
    info.singlePriceTotal = (info.pr_num*info.single_price*1).toFixed(2);
    info.detail_remark = this.data.tszhcontent;
    util.hideBuyModal(this,"isInput");
    this.setData({
      ["goodList[" + this.data.inputIndex + "]"]: info
    });
    app.globalData.dingdan_show = 1;  //返回订单页面是否刷新
    app.globalData.caigou_shua=1;  //返回订单页面是否刷新  
    app.myMethod.updataDingdanGood(info.id, this.data.id, info.pr_num, this.data.tszhcontent);
    if(info.pr_num==0 || this.data.is_enquiry==1){
      app.UpAsso('java_order/update_order_allow_batch/'+this.data.id, //订单关联
        function (ress) {   
      });
      this.onloadDetail(); 
    };
  },
  // 修改退单数量
  shop_rn_conf:function(){
    if (this.data.inputNum == '') {
      this.setData({
        inputNum:this.data.tannum
      });
    };  
    var info = this.data.info.goodList[this.data.inputIndex];
    var default_num=this.data.info.is_single==1 && this.data.info.is_nuified_num==1?info.single_num:info.need_num;
    default_num=default_num*1-Math.abs(info.return_num*1)-info.loss_num*1;  //减去退货量和损溢量
    if (this.data.inputNum*1>default_num*1){
      wx.showToast({
        title:'大于全退的值',
      })
      return;
    };
    info.myreturn_num=this.data.inputNum * 1;
    util.hideBuyModal(this,"isInput");
    this.setData({
      ["goodList[" + this.data.inputIndex + "]"]: info
    });
    var is_checked=this.data.is_checked;
    if(info.myreturn_num>0){
      is_checked[this.data.inputIndex]=true;
    }
    var check_len=Object.keys(is_checked).length;
    if(check_len==this.data.info.type_count*1-this.data.return_len*1){
      this.setData({
        count:check_len,
        isChooseAll:true,
        is_checkall:true,
        is_checked:is_checked
      });
    }else{
      this.setData({
        count:check_len,
        isChooseAll:false,
        is_checkall:false,
        is_checked:is_checked
      });
    }; 
  },
  // 修改实际收货量(入库)
  shop_shou_conf:function(){
    if (this.data.inputNum == '') {
      this.setData({
        inputNum:this.data.tannum
      });
    }
    var info = this.data.info.goodList[this.data.inputIndex];
    if (this.data.inputNum>9999.99){
      wx.showToast({
        title: '数量过大',
      })
      return;
    };
    console.log(this.data.inputNum);
    
    var all_shou=this.data.all_shou*1;
    if(info.shou_num_xj){
      all_shou-=info.shou_num_xj*1;
    };
    info.shou_num=this.data.inputNum * 1;
    var shou_num_arr=this.data.shou_num_arr;
    shou_num_arr[this.data.inputIndex]=info.shou_num;
    if(this.data.info.is_single==1 && this.data.info.is_nuified_num==1){
      info.shou_num_xj=(this.data.inputNum*1)*(info.single_price*1);
    }else{
      info.shou_num_xj=(this.data.inputNum*1)*(info.unit_price*1);
    }; 
    info.shou_num_xj=info.shou_num_xj.toFixed(2);
    all_shou+=info.shou_num_xj*1;
    util.hideBuyModal(this,"isInput");
    this.setData({
      all_shou:all_shou.toFixed(2),
      isshou_show:true,
      ["goodList[" + this.data.inputIndex + "]"]: info
    });
  },
  // 去挂单
  tohanging:function(){
    var that = this;
    wx.showModal({
      title: '确认挂单',
      content: '挂单后,供应商则不能收货\n待供应商修改提交后,由客户收货',
      success: function (res) {
        if (res.confirm) {
          wx.request({  
            url: app.globalData.url + 'set_hanging_order/'+that.data.id+'/+1',
            method: "GET",
            success: function(res) {
              console.log(JSON.stringify(res.data));  
              wx.showToast({
                title: res.data.msg, 
                duration: 500,
                success: function () {
                  app.globalData.toneed_order=0;
                  app.globalData.dingdan_show=1;
                  app.globalData.caigou_shua=1; 
                  that.onloadDetail();      
                }
              });
            }
          }); 
        }
      }
    });  
  },
  // 收货并入库
  shou_in_ku:function(){
    var that=this;
    that.one_key_fill();
    var new_arr = this.data.shou_num_arr.filter(function (item) {  //数组过滤
      //元素值，元素的索引，原数组。    
      return item>=0;       
    });
    if(new_arr.length!=this.data.goodList.length){
      wx.showLoading({
        title:'还有'+(this.data.goodList.length-new_arr.length)+'个未填写',
        duration:500
      });
      return;
    };
    var pr_money=that.data.info.is_single==1 && that.data.info.is_nuified_num==1?that.data.info.singlePriceTotal:that.data.info.total_money;  
    console.log(pr_money);
    console.log(that.data.shou_num_arr) //实收数组
    if(that.data.title_index==1){
      wx.showModal({
        title: '提示',
        content: '请确认收货',
        success: function (res) {
          if (res.confirm) {
            app.AppHttp('api/Order/FinishRecevingForCheck', { 
              openid:app.globalData.openid, 
              id:that.data.id,
              pr_nums:that.data.shou_num_arr,
              pr_money:pr_money
            }, function (res) {
              console.log(JSON.stringify(res.data));   
              app.globalData.toneed_order=0;
              app.globalData.dingdan_show=1;
              that.setData({
                order_status:7,
                ishint_ping:true,
                ['info.is_client_receive']:1
              });
              that.onloadDetail();
            });
          }
        }
      });    
    }else if(that.data.title_index==2){
      if(that.data.check_type=='receipt_order' && that.data.check_step==-1){
        wx.showModal({
          title: '提示',
          content: '请确认收货并入库',
          success: function (res) {
            if (res.confirm) {
              app.AppHttp('api/Order/ApiBatchPutStrock', {  
                openid:app.globalData.openid,
                id:that.data.id,
                pr_nums:that.data.shou_num_arr,
                pr_money:pr_money
              }, function (res) {
                console.log(JSON.stringify(res.data));  
                app.globalData.toneed_order=0; 
                app.globalData.caigou_shua=1;  
                that.setData({
                  order_status:7,
                  ishint_ping:true,
                  ['info.is_client_receive']:1,
                  ['info.is_in']:1
                }); 
                that.onloadDetail();    
              });
            }
          }
        });  
      }else if(that.data.check_type=='receipt_order' && that.data.check_step>-1){
        wx.showModal({
          title: '提示',
          content: '请确认收货，并提交审核',
          success: function (res) {
            if (res.confirm) {
              app.AppHttp('api/Order/OrderReceipt', {  
                openid:app.globalData.openid,
                id:that.data.id,
                pr_nums:that.data.shou_num_arr,
                pr_money:pr_money
              }, function (res) {
                console.log(JSON.stringify(res.data));  
                app.globalData.dingdan_show=1;
                app.globalData.caigou_shua=1;  
                that.check_list(4);
                that.setData({
                  ishint_ping:true,
                  ['info.is_client_receive']:1
                });  
                that.onloadDetail();   
              });
            }
          }
        });  
      }   
    };
  },
  // 关闭点评提示
  cancel_hint_ping:function(){
    this.setData({
      ishint_ping:false
    });
  },
  // 收货后仅入库
  kuguan_in_ku:function(){
    var that = this;
    wx.showModal({
      title: '提示',
      content: '请确认入库',
      success: function (res) {
        if (res.confirm) {
          app.AppHttp('api/Order/OrderBatchPutStrock', {  
            openid:app.globalData.openid,
            id:that.data.id          
          }, function (res) {
            console.log(JSON.stringify(res.data));   
            app.globalData.caigou_shua=1;  
            that.setData({
              ['info.is_in']:1
            }); 
          });
        }
      }
    }); 
  },
  // 撤回订单到0
  conf_return_zero:function(){
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认撤回？',
      success: function (res) {
        if (res.confirm) {
          app.AppHttp('api/Order/changeOrderStatus', {  
            openid:app.globalData.openid,
            id: that.data.id,
            status:0
          }, function (res) {
            that.setData({
              order_status:0
            });
            that.onloadDetail();  
          });
        }
      }
    }); 
  },
  // 自填报价
  me_fill_baijia:function(){
    this.setData({
      isme_fill:true
    });
  },
  // 自填报价返回
  back_me_fill:function(){
    this.setData({
      isme_fill:false
    });
  },
  // 供应商报价
  super_baojia:function(){
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认供应商报价',
      success: function (res) {
        if (res.confirm) {
          app.AppHttp('api/Order/changeOrderStatus', {  
            openid:app.globalData.openid,
            id: that.data.id,
            status:1
          }, function (res) {
            that.setData({
              order_status:1
            });
            that.onloadDetail();  
          });
        }
      }
    });  
  },
  // 收货完成（order-status==5）
  shou_fin_conf:function(){
    var that=this;
    wx.showModal({
      title: '提示',
      content: '请核对实物送货单与线上送货单保持一致，财务审核后，订单将锁定，不再允许修改！',
      success: function (res) {
        if (res.confirm) {
          app.AppHttp('api/Order/changeOrderStatus', {  
            openid:app.globalData.openid,
            id: that.data.id,
            status:7
          }, function (res) {
            if(that.data.title_index==1){
              app.globalData.dingdan_show = 1;  //返回订单页面是否刷新     
            }else if(that.data.title_index==2){
              app.globalData.caigou_shua=1;  //返回订单页面是否刷新      
            };
            wx.navigateBack({
              delta:1
            });     
          });
        }
      }
    });  
  },
  // 一键填充(入库)
  one_key_fill:function(){
    var all_shou=0;
    var goodList=this.data.goodList;
    var shou_num_arr=this.data.shou_num_arr; 
    for(var i=0;i<goodList.length;i++){
      if(!goodList[i].shou_num && goodList[i].shou_num!=0){
        goodList[i].shou_num=this.data.info.is_single==1 && this.data.info.is_nuified_num==1?goodList[i].single_num*1:goodList[i].need_num*1;
      }; 
      shou_num_arr[i]=goodList[i].shou_num;
      if(this.data.info.is_single==1 && this.data.info.is_nuified_num==1){      
        goodList[i].shou_num_xj=(goodList[i].shou_num)*(goodList[i].single_price*1).toFixed(2);
      }else{
        goodList[i].shou_num_xj=(goodList[i].shou_num)*(goodList[i].unit_price*1).toFixed(2);
      };
      goodList[i].shou_num_xj=goodList[i].shou_num_xj.toFixed(2);  
      all_shou+=goodList[i].shou_num_xj* 1; 
    };
    this.setData({
      isshou_show:true,
      goodList:goodList,
      all_shou:all_shou.toFixed(2)
    });
  },
  // 打开订单备注
  open_remark_or:function(){
    if(this.data.order_status<0 && this.data.use_person_id==this.data.info.person_id){
      this.setData({
        isOrderremark:true,
        order_remark:this.data.info.order_remark?this.data.info.order_remark:''
      });
    }else{
      wx.showModal({
        title: '订单备注',
        content: this.data.info.order_remark,
        showCancel: false,
        confirmText: "确定",
        confirmColor: "#19a751",
        success: function (sm) {
          if (sm.confirm) {
            // 用户点击了确定 可以调用删除方法了
          } else if (sm.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    };
  },
  // 输入订单备注
  beizhuinput:function(e){
    this.setData({
      order_remark: e.detail.value
    });
  },
  // 关闭订单备注
  confirmNOkClick:function(){
    this.setData({
      isOrderremark: false
    })
  },
  // 备注确定
  confirmOkClick:function(){
    var that=this;
    var id = that.data.id;
    wx.request({
      url: app.globalData.url + 'api/Order/changeRemark',
      method: "POST",
      data: {
        id: id,
        order_remark: that.data.order_remark
      },
      success: function (res) {
        console.log(res.data);
        wx.showToast({
          title: res.data.msg,
          duration: 500
        })
        if (res.data.status == 1) {
          that.setData({
            isOrderremark: false,
            ['info.order_remark']:that.data.order_remark
          });      
        };
      }
    })
  },
  // 单选
  outChange:function(e){
    var is_checked = {};
    for (var i = 0; i < e.detail.value.length; i++) {
      is_checked[e.detail.value[i]] = true;
    };
    if(e.detail.value.length==this.data.info.type_count*1-this.data.return_len*1){
      this.setData({
        count:e.detail.value.length,
        isChooseAll:true,
        is_checkall:true,
        is_checked:is_checked,
      });
    }else{
      this.setData({
        count:e.detail.value.length,
        isChooseAll:false,
        is_checkall:false,
        is_checked:is_checked
      });
    };
  },
  // 全选
  out_all_chose:function(){
    if (!this.data.isChooseAll == false) {
      this.setData({
        is_checked:{}
      })
    };
    this.setData({
      isChooseAll: !this.data.isChooseAll,
      is_checkall: !this.data.isChooseAll,
      count:!this.data.isChooseAll == true ? this.data.info.type_count*1-this.data.return_len*1:0
    });
  },
  // 表单提交
  formSubmit:function(e){
    var goodList=this.data.goodList;
    var ids=[];
    var nums=[];
    var price_arr=[];
    if(e.detail.target.dataset.sub=='total_return'){ //全退
      for (var i = 0; i < goodList.length; i++) {
        // 减去退货量和损溢量
        if(goodList[i].refer_num*1-Math.abs(goodList[i].return_num*1)-goodList[i].loss_num*1>0){
          ids.push(goodList[i].id); 
          nums.push(goodList[i].refer_num*1-Math.abs(goodList[i].return_num*1)-goodList[i].loss_num*1);
        };     
      };
      this.setData({
        isreturn_sub:true,
        ids:ids,
        nums:nums
      });
      return; 
    }else{  
      for (var i = 0; i < e.detail.value.chose.length; i++) {
        ids.push(goodList[e.detail.value.chose[i]].id);
        if(e.detail.target.dataset.sub=='return'){  
          if(goodList[e.detail.value.chose[i]].myreturn_num){
            nums.push(goodList[e.detail.value.chose[i]].myreturn_num);
          }else{    
            wx.showLoading({
              title: '请输入退货量',
              duration:500
            });   
            return; 
          }; 
        };    
        if(e.detail.target.dataset.sub=='turn' && this.data.isme_fill==true){  
          var offer_price_list=this.data.offer_price_list;
          if(offer_price_list[e.detail.value.chose[i]]){
            price_arr.push(offer_price_list[e.detail.value.chose[i]]);   
          }else{    
            wx.showLoading({
              title: '请输入价格',
              duration:500
            });   
            return; 
          }; 
        }; 
      };  
    };  
    if(e.detail.value.chose.length==0){
      wx.showLoading({
        title: '请至少选择一项',
        duration: 500
      });
      return;
    }
    if(e.detail.target.dataset.sub=='return'){  //提交退单
      this.setData({
        isreturn_sub:true,
        ids:ids,
        nums:nums
      })
    }else if(e.detail.target.dataset.sub=='turn'){  //询价单确认下单
      this.setData({
        ids:ids,
        price_arr:price_arr
      });
      this.cai_submit_but();
    };
  },
  // 完成询价
  fin_off_ck:function(){
    var that = this;
    wx.showModal({
      title: '提示',
      content: '请确认完成询价',
      success: function (res) {
        if (res.confirm) {
          app.AppHttp('api/Client/finishEnquiryOrder', {  
            id:that.data.id
          }, function (res) {
            console.log(JSON.stringify(res.data));  
            app.globalData.dingdan_show=1;
            app.globalData.caigou_shua=1;
            wx.navigateBack({
              delta:1
            });
          });
        };
      }
    });   
  },
  // 关闭提交退单
  return_sub_cancel:function(){
    this.setData({
      isreturn_sub:false
    });
  },
  // 确认提交退单
  return_sub_conf:function(){
    var that = this;
    let nums=that.data.nums.map(function(item){
      item=item*(-1);
      return item;
    });
    util.buttonClicked(this);  //防止重复点击
    app.AppHttp('api/Order/returnOrderGoods', {  
      openid: app.globalData.openid,
      ids:that.data.ids,
      nums:nums
    }, function (res) {
      console.log(JSON.stringify(res.data));
      if(that.data.info.zicai_id>0){
        app.globalData.dingdan_show=1;
        app.globalData.caigou_shua=1;
      }else{
        that.valid_news(res.data.data);
      };
      wx.navigateBack({
        delta:1
      });
    });
  },
  focus_ck:function(){
    this.setData({
      showfocus:true
    });
  },
  focus_ck1:function(e){
    var focus=e.currentTarget.dataset.focus;
    if(this.data.item_info.price_type>3 && (focus==1 || focus==3)){
      if(e.currentTarget.dataset.price_zero>0){
        return;
      };    
    }
    this.setData({
      focus:e.currentTarget.dataset.focus
    });
  },
  // 自填询价单
  open_offck:function(e){
    let index = e.currentTarget.dataset.index;
    let pr_info = this.data.goodList[index];
    this.setData({
      is_offchange:true,
      showfocus:true,
      tanname: pr_info.pr_name,
      change_off_index:index,
      input_offprice:''
    });
  },
  // 输入报价
  setbaoPrice:function(e){
    var input_offprice;
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) { //正则验证，提现金额小数点后不能大于1位数字
      input_offprice = e.detail.value;
    } else {
      input_offprice = e.detail.value.substring(0, e.detail.value.length - 1);
    };
    this.setData({
      input_offprice: input_offprice[0]=='.'?'0'+input_offprice:input_offprice
    });
  },
  // 关闭报价
  cancel_baojia:function(){
    this.setData({
      is_offchange:false
    });
  },
  // 确定修改价格
  conf_baojia:function(){
    if(this.data.input_offprice==''){
      wx.showLoading({
        title:'请填写价格',
        duration:500
      });
      return;
    };
    var offer_price_list=this.data.offer_price_list;
    offer_price_list[this.data.change_off_index]=this.data.input_offprice;
    var is_checked=this.data.is_checked;
    if(offer_price_list[this.data.change_off_index]>=0){
      is_checked[this.data.change_off_index]=true;
    };
    var check_len=Object.keys(is_checked).length;
    if(check_len==this.data.info.type_count*1){
      this.setData({
        count:check_len,
        isChooseAll:true,
        is_checkall:true,
        is_checked:is_checked
      });
    }else{
      this.setData({
        count:check_len,
        isChooseAll:false,
        is_checkall:false,
        is_checked:is_checked
      });
    }; 
    this.setData({
      is_offchange:false,
      offer_price_list:offer_price_list
    }); 
  },
  // 询价单转正式单生成
  cai_submit_but:function(){
    var that = this;
    console.log(that.data.ids);
    console.log(that.data.price_arr);
    wx.showModal({
      title: '提示',
      content: '请确认下单',
      success: function (res) {
        if (res.confirm) {
          app.AppHttp('api/Order/createOrderFromEnquiry', {
            openid: app.globalData.openid,
            detail_ids:that.data.ids,
            price_arr:that.data.price_arr
          }, function (res) {
            console.log(JSON.stringify(res.data));
            that.valid_news(res.data.data);
            app.globalData.dingdan_show = 1;  //返回订单页面是否刷新 
            app.globalData.caigou_shua=1; 
            wx.navigateBack({
              delta:1
            });
          });
        };
      }
    });  
  },
  /**
  * 查看备注
  */
  showRemark: function (e) {
    let remark = e.currentTarget.dataset.remark;
    wx.showModal({
      title: '备注',
      content: remark,
      showCancel: false,
      confirmText: "确定",
      confirmColor: "#19a751",
      success: function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用删除方法了
        } else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 调整量和单价弹窗
   */
  itemClick(e){
    let that = this;
    let item_info = e.currentTarget.dataset.id;
    console.log(item_info);
    if(item_info.price_type>3 && item_info.unit_price>0 && item_info.is_hand_change==0 && item_info.is_price==1){  //价格锁定
      that.setData({
        is_change:2
      });
    }else{
      that.setData({
        is_change:1
      });
    };
    that.setData({
      specsunit:'',
      focus:null,
      item_info: item_info,
      detail_id: item_info.id,
      isInput_bei: true,
      inputneedNum:'',
      inputPrice: ''
    });  
  },
  /**
   * 设置分拣量
   */
  setneedNumber: function (e) {
    var inputneedNum;
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) { //正则验证，提现金额小数点后不能大于2位数字
      inputneedNum = e.detail.value;
    } else {
      inputneedNum = e.detail.value.substring(0, e.detail.value.length - 1);
    };
    this.setData({
      inputneedNum: inputneedNum[0]=='.'?'0'+inputneedNum:inputneedNum
    });
  },
  /**
   * 设置价格
   */
  setPrice: function (e) {
    var inputPrice;
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) { //正则验证，提现金额小数点后不能大于2位数字
      inputPrice = e.detail.value;
    } else {
      inputPrice = e.detail.value.substring(0, e.detail.value.length - 1);
    };
    this.setData({
      inputPrice: inputPrice[0]=='.'?'0'+inputPrice:inputPrice
    });
  },
  /**
   * 取消弹窗
   */
  cancelCilck: function () {
    let that = this;
    wx.hideKeyboard();
    that.setData({
      isInput_bei: false,
      inputneedNum: '',
      inputPrice: ''
    })
  },
  /**
   * 确定修改
   */
  confirmClick: function () {
    let that = this;
    let item_info = that.data.item_info;
    let inputPrice, unitindex;
    inputPrice = that.data.inputPrice;
    if (that.data.item_info.true_unit != that.data.item_info.pr_unit && that.data.item_info.true_unit != 0) {
      unitindex = that.data.unitindex;
    } else {
      unitindex = that.data.item_info.pr_unit;
    };  
    if(that.data.info.group_id>0 && that.data.item_info.good_id[0]!="F" && that.data.item_info.true_unit!=that.data.item_info.original_good_unit && that.data.item_info.help_unit>0){
      wx.showLoading({
        title:'请修改单位',
        duration:500
      })
      return;
    };
    if (inputPrice == '') {
      if(parseFloat(item_info.unit_price)==0){
        wx.showLoading({
          title:'未填写单价',
          duration:500
        })
        return;
      };
      inputPrice = item_info.unit_price;   
    }; 
    if (that.data.inputneedNum==''){
      that.data.inputneedNum = item_info.need_num;
    };
    app.AppHttp('api/Orders/changeSingleNum', {
      id: that.data.detail_id,
      unit_price: inputPrice,
      need_num:parseFloat(that.data.inputneedNum),
      single_num:parseFloat(that.data.inputneedNum),
      single_price:inputPrice,
      true_unit: unitindex,
      change_type:'',
      is_change:that.data.is_change
    }, function (res) {   
      console.log(JSON.stringify(res.data));
      if (res.data.status == 1) {     
        wx.showToast({
          title: '修改成功',
          duration: 500,
          success: function () {
            wx.hideKeyboard();
            that.setData({
              isInput_bei: false,
              inputneedNum: '',
              inputPrice: '',
              specsunit: '',
            });
            that.onloadDetail();
          }
        });
      }
    })
  },
  /***
   * 完成备货
   */
  finishReady: function () {
    let that = this;
    let info = that.data.info;
    var tostatus=4;
    if(info.return_type==2){
      tostatus=7;   //终审权限关闭
    };
    wx.showModal({
      title: '提示',
      content: '请确认完成',
      success: function (res) {
        if (res.confirm) {
          if (info.sorting_status == 1) {
            if (info.price_status == 1) {
              app.AppHttp('api/Orders/StatusChange', {
                id:that.data.id,
                order_status:tostatus,
                openid: app.globalData.openid
              }, function (res) {
                console.log(JSON.stringify(res.data))
                if (res.data.status == 1) {
                  app.globalData.dingdan_show = 1;  //返回订单页面是否刷新
                  app.globalData.caigou_shua=1;
                  app.AppHttp('api/Order/changeOrderStatus', {  
                    openid:app.globalData.openid,
                    id: that.data.id,
                    status:7
                  }, function (res) {
                    wx.showToast({
                      title: res.data.msg,
                      duration: 500
                    });
                    that.setData({
                      order_status:7
                    });
                    that.onloadDetail(); 
                  });
                }
              })
            } else {
              wx.showToast({
                title: '改价未完成',
                icon: 'loading',
                duration: 500
              })
            }
          } else {
            wx.showToast({
              title: '分拣未完成',
              icon: 'loading',
              duration: 500
            })
          }
        }
      }
    }); 
  },
  /**
   * 设置单位
   */
  changeCilck: function () {
    let that = this;
    var item_info=that.data.item_info;
    if(that.data.info.group_id>0 && item_info.good_id[0]!='F'){  //企业（需排除非标品的情况）
      if(item_info.true_unit==item_info.original_good_unit || item_info.help_unit==0 || !item_info.help_unit){
        return;
      };
      console.log(item_info);
      console.log(item_info.unit_name);
      var help_unit=item_info.help_unit;
      var help_unit_name=item_info.help_unit_name;
      if(help_unit>0){  //有辅助单位
        util.showBuyModal(that);
        that.setData({
          selectdanwei: true
        });
        var unit_list={};
        unit_list[item_info.original_good_unit]=item_info.original_good_unit_name;
        that.setData({
          unit_list:unit_list
        });
        console.log(unit_list);
      };
    }else{    //非企业+非标品
      util.showBuyModal(that);
      that.setData({
        selectdanwei: true
      });
      wx.request({
        url: app.globalData.url + 'api/Supplier/unit_list',
        method: 'GET',
        data: {
          // good_id:that.data.item_info.good_id
        },
        success: function(res) {
          that.setData({
            unit_list: res.data
          });
          console.log(JSON.stringify(res.data));
        }
      });
    }
  },
  /**
   * 关闭单位弹窗
   */
  closedanwei: function () {
    util.hideBuyModal(this,"selectdanwei");
  },
  /** 
   * 更改单位
   * */
  addunit: function (e) {
    util.hideBuyModal(this,"selectdanwei");
    this.setData({
      specsunit: e.target.dataset.unitname,
      unitindex: e.target.dataset.index,
      ["item_info.true_unit"]:e.target.dataset.index
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {  
    this.onloadDetail();  
    var that = this;
    var mconnectionstate = plugin.getconnectionstate(); //设备连接状态
    if (mconnectionstate) {
      that.setData({
        connectionstate: "已连接"
      })
    } else {
      that.setData({
        connectionstate: "未连接"
      });
    }
    wx.getConnectedBluetoothDevices({
      success(res) {
        console.log(res.devices);
        for (var i = 0; i < res.devices.length; i++) {
          if (res.devices[i].name == 'WXL-T12') {
            that.setData({
              cont: "已连接"
            })
          }
        }
      },
      fail: function () {
        that.setData({
          connectionstate: "未连接",
          cont: "未连接"
        })
      }
    });
  },
  // 启用蓝牙秤
  openweight: function () {
    if (this.data.cont == '已连接') {
      this.data.setInter = setInterval(this.change, 500);
      this.setData({
        weightstatus: true
      })
    } else {
      wx.showLoading({
        title: '蓝牙秤未连接',
        duration: 500,
        success: function() {
          wx.navigateTo({
            url: '/packageA/pages/bluetooch/bluetooch'
          })
        }
      });
    }
  },
  // 关闭蓝牙秤
  closeweight: function () {
    clearInterval(this.data.setInter);
    this.setData({
      content: "",
      weightstatus: false
    })
  },
  // 蓝牙秤上重量的动态变化
  change: function () {
    this.setData({
      content: parseFloat(app.globalData.weight.toFixed(2))
    });
    this.setValue();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if(complete_ck==false){
      console.log(dingdanPage.data.status);
      console.log(this.data.d_index);
        console.log(this.data.order_status)
      if(this.data.entPage==1){
        dingdanPage.setData({
          ["datas[" + this.data.d_index + "].order_status"]:this.data.order_status,
          ["datas[" + this.data.d_index + "].types"]:this.data.goodList.length//更新数量
        });
      }else if(!this.data.entPage && dingdanPage.data.status<=1){  //新单           
        dingdanPage.setData({
          ["helist[" + this.data.d_index + "].current_id"]:this.data.order_status<0?null:this.data.check_list.current_personal,
          ["helist[" + this.data.d_index + "].order_status"]:this.data.order_status,
          ["helist[" + this.data.d_index + "].types"]:this.data.goodList.length//更新数量
        });
      }else if(!this.data.entPage && dingdanPage.data.status>1){  //备货后
        dingdanPage.setData({
          ["datas[" + this.data.d_index + "].settle_accounts"]:this.data.info.settle_accounts,
          ["datas[" + this.data.d_index + "].order_status"]:this.data.order_status,
          ["datas[" + this.data.d_index + "].types"]:this.data.goodList.length//更新数量
        });
      };
    };
  },
  // 检测商城功能是否开放
  get_SupplierOpenFunc(){
    let that = this;
    app.AppHttp('api/Client/supperDetail', {  
      openid: app.globalData.openid,
      id: that.data.info.supplier_id
    }, function (res) {
      if(res.data.data.status==1){
        app.AppHttp('api/Supplier/getSupplierOpenFunc', {
          supplier_id: that.data.info.supplier_id
        }, function(res) {
          if(!res.data.supplierFind){
            wx.showModal({
              title:'提示',
              content:'此供应商不存在',
              showCancel: false,
              confirmText:"我知道了",
              success: function (res) {}
            }); 
            return;
          };
          let is_store_disable = false;
          let SupplierOpenFunFind = {
            "store_status":"0",
            "store_try_time":"0",
            "store_open_time":"0",
            "store_due_time":"0",
          };
          if(res.data.SupplierOpenFunFind){
            SupplierOpenFunFind = res.data.SupplierOpenFunFind;
          };
          if(res.data.supplierFind.level==4){
            if(SupplierOpenFunFind.store_status==2 && res.data.supplierFind.is_open_dir==1){
              if(SupplierOpenFunFind.store_due_time>0 && util.due_Date(SupplierOpenFunFind.store_due_time)>0){
                is_store_disable = false;
              }else{
                is_store_disable = true;
              };
            }else if(SupplierOpenFunFind.store_status==1 && res.data.supplierFind.is_open_dir==1){
              if(SupplierOpenFunFind.store_try_time>0 && util.due_Date(SupplierOpenFunFind.store_try_time)>0){
                is_store_disable = false;
              }else{
                is_store_disable = true;
              };
            }else{
              is_store_disable = true;
            };
          };
          that.setData({
            is_store_disable:is_store_disable
          });
          let postDataArr = that.data.goodList.map(function(item) {
            let postItem={};
              postItem['trade_name']=item.pr_name;
              postItem['pr_num']=item.need_num;
              postItem['unit_name']=item.true_unit_name!='无'?item.true_unit_name:item.unit_name;
            return postItem;
          });
          app.globalData.postDataArr = postDataArr;
          wx.showModal({
            title: '提示',
            content: '确定再来一单',
            success: function (res) {
              if (res.confirm) {
                that.toRecord();
              };
            }
          });
        });
      }else{
        wx.showModal({
          title:'提示',
          content:'合作关系暂停或已停止',
          showCancel: false,
          confirmText:"我知道了",
          success: function (res) {}
        }); 
      }
    })   
  },
  // 再来一单（前往录单）
  toRecord(){
    wx.navigateTo({
      url: '/record_space/pages/record_list/record_list?supplier_name='+this.data.info.company_name+'&supplier_id='+this.data.info.supplier_id+'&good_dir_set='+app.globalData.loginInfo.good_dir_set+'&client_is_store='+app.globalData.loginInfo.client_is_store+'&purchase_type='+app.globalData.loginInfo.purchase_type+'&is_store_disable='+this.data.is_store_disable+'&is_again='+1
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function(){
    this.onShow();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})